<template>
  <div class="detection-models-container">
    <el-card class="filter-card">
      <div class="filter-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="模型名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入模型名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="模型格式">
            <el-select
              v-model="searchForm.format"
              placeholder="请选择模型格式"
              clearable
              style="width: 150px"
            >
              <el-option label="YOLOv8" value="YOLOv8" />
              <el-option label="Mask R-CNN" value="Mask R-CNN" />
              <el-option label="SegFormer" value="SegFormer" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.is_active"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="激活" :value="true" />
              <el-option label="未激活" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click="resetSearch">
              重置
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="handleAddModel">
              <el-icon><Plus /></el-icon>
              添加模型
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="data-card">
      <el-table
        v-loading="loading"
        :data="modelsData"
        style="width: 100%"
        @row-dblclick="handleEditModel"
      >
        <el-table-column prop="id" label="模型ID" width="80" />
        <el-table-column prop="name" label="模型名称" width="200">
          <template #default="{ row }">
            <span style="font-weight: bold;">{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="format" label="模型格式" width="120" />
        <el-table-column prop="application_scenario" label="适用场景" width="250">
          <template #default="{ row }">
            <el-tooltip :content="row.application_scenario" placement="top">
              <span>{{ truncateText(row.application_scenario, 30) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="当前版本" width="150">
          <template #default="{ row }">
            <el-tag v-if="row.current_version" type="success" size="small">
              {{ row.current_version.version_name }}
            </el-tag>
            <span v-else class="text-muted">未设置</span>
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.is_active"
              :active-value="true"
              :inactive-value="false"
              @change="handleToggleActive(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleViewVersions(row)"
              :disabled="viewingId === row.id"
            >
              版本管理
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="handleEditModel(row)"
              :disabled="editingId === row.id"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteModel(row)"
              :disabled="deletingId === row.id"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑模型对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加检测模型' : '编辑检测模型'"
      width="700px"
      destroy-on-close
    >
      <el-form
        :model="modelForm"
        :rules="modelRules"
        ref="modelFormRef"
        label-width="120px"
      >
        <el-form-item label="模型名称" prop="name">
          <el-input
            v-model="modelForm.name"
            placeholder="请输入模型名称"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="模型格式" prop="format">
          <el-select
            v-model="modelForm.format"
            placeholder="请选择模型格式"
          >
            <el-option label="YOLOv8" value="YOLOv8" />
            <el-option label="Mask R-CNN" value="Mask R-CNN" />
            <el-option label="SegFormer" value="SegFormer" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="模型描述" prop="description">
          <el-input
            v-model="modelForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入模型描述"
          />
        </el-form-item>
        <el-form-item label="适用场景" prop="application_scenario">
          <el-input
            v-model="modelForm.application_scenario"
            type="textarea"
            :rows="4"
            placeholder="如：管道泄漏、电力线破损等"
          />
        </el-form-item>
        <el-form-item label="输入要求" prop="input_requirements">
          <el-input
            v-model="modelForm.input_requirements"
            type="textarea"
            :rows="3"
            placeholder="如：图片分辨率、视频格式等"
          />
        </el-form-item>
        <el-form-item label="输出格式" prop="output_format">
          <el-input
            v-model="modelForm.output_format"
            type="textarea"
            :rows="3"
            placeholder="如：坐标+置信度等"
          />
        </el-form-item>
        <el-form-item label="是否激活" prop="is_active">
          <el-switch v-model="modelForm.is_active" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="dialogLoading"
          >
            {{ dialogLoading ? '提交中...' : '确定' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 版本管理对话框 -->
    <el-dialog
      v-model="versionsVisible"
      :title="`${currentModel?.name || ''} - 版本管理`"
      width="800px"
      destroy-on-close
    >
      <div class="versions-management">
        <div class="versions-header">
          <el-button type="success" @click="handleAddVersion">
            <el-icon><Plus /></el-icon>
            添加版本
          </el-button>
        </div>
        <el-table
          v-loading="versionsLoading"
          :data="currentModelVersions"
          style="width: 100%"
        >
          <el-table-column prop="id" label="版本ID" width="80" />
          <el-table-column prop="version_name" label="版本名称" width="150" />
          <el-table-column prop="version_code" label="版本号" width="100" />
          <el-table-column prop="accuracy" label="准确率" width="100" />
          <el-table-column prop="recall" label="召回率" width="100" />
          <el-table-column prop="description" label="版本描述">
            <template #default="{ row }">
              <el-tooltip :content="row.description" placement="top">
                <span>{{ truncateText(row.description, 50) }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="是否当前版本" width="120">
            <template #default="{ row }">
              <el-tag v-if="currentModel?.current_version_id === row.id" type="primary" size="small">
                是
              </el-tag>
              <span v-else class="text-muted">否</span>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180" />
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button
                v-if="currentModel?.current_version_id !== row.id"
                type="primary"
                size="small"
                @click="handleActivateVersion(row)"
                :disabled="!row.is_active"
              >
                设为当前版本
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="handleEditVersion(row)"
                :disabled="editingVersionId === row.id"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDeleteVersion(row)"
                :disabled="deletingVersionId === row.id"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="versionsVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加/编辑版本对话框 -->
    <el-dialog
      v-model="versionDialogVisible"
      :title="versionDialogType === 'add' ? '添加模型版本' : '编辑模型版本'"
      width="600px"
      destroy-on-close
    >
      <el-form
        :model="versionForm"
        :rules="versionRules"
        ref="versionFormRef"
        label-width="120px"
      >
        <el-form-item label="版本名称" prop="version_name">
          <el-input
            v-model="versionForm.version_name"
            placeholder="如：V1.0基础版、V1.1优化版"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="版本号" prop="version_code">
          <el-input
            v-model="versionForm.version_code"
            placeholder="如：1.0.0"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="准确率" prop="accuracy">
          <el-input
            v-model="versionForm.accuracy"
            placeholder="如：95%"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="召回率" prop="recall">
          <el-input
            v-model="versionForm.recall"
            placeholder="如：90%"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="版本描述" prop="description">
          <el-input
            v-model="versionForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入版本描述"
          />
        </el-form-item>
        <el-form-item label="是否激活" prop="is_active">
          <el-switch v-model="versionForm.is_active" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="versionDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmitVersion"
            :loading="versionDialogLoading"
          >
            {{ versionDialogLoading ? '提交中...' : '确定' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import axios from 'axios'

// 状态管理
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const dialogLoading = ref(false)
const editingId = ref(null)
const deletingId = ref(null)
const viewingId = ref(null)

// 搜索表单
const searchForm = reactive({
  name: '',
  format: '',
  is_active: null
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 模型数据
const modelsData = ref([])

// 表单数据
const modelForm = reactive({
  name: '',
  description: '',
  format: '',
  application_scenario: '',
  input_requirements: '',
  output_format: '',
  is_active: true
})

// 表单验证规则
const modelRules = {
  name: [
    { required: true, message: '请输入模型名称', trigger: 'blur' },
    { min: 1, max: 200, message: '名称长度在 1 到 200 个字符', trigger: 'blur' }
  ],
  format: [
    { required: true, message: '请选择模型格式', trigger: 'change' }
  ],
  application_scenario: [
    { required: true, message: '请输入适用场景', trigger: 'blur' }
  ]
}

// 版本管理相关状态
const versionsVisible = ref(false)
const versionsLoading = ref(false)
const currentModel = ref(null)
const currentModelVersions = ref([])
const versionDialogVisible = ref(false)
const versionDialogType = ref('add')
const versionDialogLoading = ref(false)
const editingVersionId = ref(null)
const deletingVersionId = ref(null)

// 版本表单数据
const versionForm = reactive({
  version_name: '',
  version_code: '',
  accuracy: '',
  recall: '',
  description: '',
  is_active: true
})

// 版本表单验证规则
const versionRules = {
  version_name: [
    { required: true, message: '请输入版本名称', trigger: 'blur' },
    { min: 1, max: 100, message: '名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  version_code: [
    { required: true, message: '请输入版本号', trigger: 'blur' },
    { min: 1, max: 50, message: '版本号长度在 1 到 50 个字符', trigger: 'blur' }
  ]
}

// 获取模型列表
const fetchModels = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/detection-models', {
      params: {
        page: pagination.currentPage,
        page_size: pagination.pageSize,
        ...searchForm
      }
    })
    
    if (response.data.code === 200) {
      modelsData.value = response.data.data.items || []
      pagination.total = response.data.data.total || 0
    } else {
      ElMessage.error(response.data.message || '获取模型列表失败')
    }
  } catch (error) {
    ElMessage.error('获取模型列表失败')
    console.error('获取模型列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchModels()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  searchForm.is_active = null
  pagination.currentPage = 1
  fetchModels()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchModels()
}

const handleCurrentChange = (current) => {
  pagination.currentPage = current
  fetchModels()
}

// 打开添加模型对话框
const handleAddModel = () => {
  dialogType.value = 'add'
  resetModelForm()
  dialogVisible.value = true
}

// 打开编辑模型对话框
const handleEditModel = (row) => {
  dialogType.value = 'edit'
  editingId.value = row.id
  // 复制数据
  Object.assign(modelForm, row)
  dialogVisible.value = true
}

// 重置模型表单
const resetModelForm = () => {
  modelForm.name = ''
  modelForm.description = ''
  modelForm.format = ''
  modelForm.application_scenario = ''
  modelForm.input_requirements = ''
  modelForm.output_format = ''
  modelForm.is_active = true
  
  // 重置表单验证
  if (modelFormRef.value) {
    modelFormRef.value.resetFields()
  }
}

// 表单引用
const modelFormRef = ref(null)

// 提交模型表单
const handleSubmit = async () => {
  if (!modelFormRef.value) return
  
  try {
    await modelFormRef.value.validate()
    dialogLoading.value = true
    
    let response
    if (dialogType.value === 'add') {
      response = await axios.post('/api/detection-models', modelForm)
    } else {
      response = await axios.put(`/api/detection-models/${editingId.value}`, modelForm)
    }
    
    if (response.data.code === 200) {
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '编辑成功')
      dialogVisible.value = false
      fetchModels()
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    if (error.name === 'Error') {
      ElMessage.error(error.response?.data?.message || '操作失败')
    }
    // 验证失败时不显示错误消息，Element Plus 会自动处理
  } finally {
    dialogLoading.value = false
  }
}

// 删除模型
const handleDeleteModel = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除模型「${row.name}」吗？删除后相关的版本数据也将被删除。`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    deletingId.value = row.id
    const response = await axios.delete(`/api/detection-models/${row.id}`)
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      fetchModels()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    // 用户取消删除时不显示错误
    if (error.name !== 'Error') {
      ElMessage.error('删除失败')
    }
  } finally {
    deletingId.value = null
  }
}

// 切换激活状态
const handleToggleActive = async (row) => {
  try {
    const response = await axios.put(`/api/detection-models/${row.id}`, {
      is_active: row.is_active
    })
    
    if (response.data.code !== 200) {
      // 恢复原状态
      row.is_active = !row.is_active
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    // 恢复原状态
    row.is_active = !row.is_active
    ElMessage.error('操作失败')
  }
}

// 查看版本管理
const handleViewVersions = async (row) => {
  currentModel.value = row
  viewingId.value = row.id
  await fetchModelVersions(row.id)
  versionsVisible.value = true
}

// 获取模型版本列表
const fetchModelVersions = async (modelId) => {
  versionsLoading.value = true
  try {
    const response = await axios.get(`/api/detection-models/${modelId}/versions`)
    
    if (response.data.code === 200) {
      currentModelVersions.value = response.data.data || []
    } else {
      ElMessage.error(response.data.message || '获取版本列表失败')
    }
  } catch (error) {
    ElMessage.error('获取版本列表失败')
    console.error('获取版本列表失败:', error)
  } finally {
    versionsLoading.value = false
  }
}

// 打开添加版本对话框
const handleAddVersion = () => {
  versionDialogType.value = 'add'
  resetVersionForm()
  versionDialogVisible.value = true
}

// 打开编辑版本对话框
const handleEditVersion = (row) => {
  versionDialogType.value = 'edit'
  editingVersionId.value = row.id
  // 复制数据
  Object.assign(versionForm, row)
  versionDialogVisible.value = true
}

// 重置版本表单
const resetVersionForm = () => {
  versionForm.version_name = ''
  versionForm.version_code = ''
  versionForm.accuracy = ''
  versionForm.recall = ''
  versionForm.description = ''
  versionForm.is_active = true
  
  // 重置表单验证
  if (versionFormRef.value) {
    versionFormRef.value.resetFields()
  }
}

// 版本表单引用
const versionFormRef = ref(null)

// 提交版本表单
const handleSubmitVersion = async () => {
  if (!versionFormRef.value || !currentModel.value) return
  
  try {
    await versionFormRef.value.validate()
    versionDialogLoading.value = true
    
    let response
    const versionData = {
      ...versionForm,
      model_id: currentModel.value.id
    }
    
    if (versionDialogType.value === 'add') {
      response = await axios.post(`/api/detection-models/${currentModel.value.id}/versions`, versionData)
    } else {
      response = await axios.put(`/api/detection-models/versions/${editingVersionId.value}`, versionForm)
    }
    
    if (response.data.code === 200) {
      ElMessage.success(versionDialogType.value === 'add' ? '添加版本成功' : '编辑版本成功')
      versionDialogVisible.value = false
      await fetchModelVersions(currentModel.value.id)
      // 刷新模型列表以更新当前版本信息
      fetchModels()
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    if (error.name === 'Error') {
      ElMessage.error(error.response?.data?.message || '操作失败')
    }
  } finally {
    versionDialogLoading.value = false
  }
}

// 激活模型版本（设为当前版本）
const handleActivateVersion = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要将「${row.version_name}」设为当前使用版本吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    const response = await axios.post(`/api/detection-models/versions/${row.id}/activate`)
    
    if (response.data.code === 200) {
      ElMessage.success('设置成功')
      await fetchModelVersions(currentModel.value.id)
      // 刷新模型列表以更新当前版本信息
      fetchModels()
    } else {
      ElMessage.error(response.data.message || '设置失败')
    }
  } catch (error) {
    // 用户取消设置时不显示错误
    if (error.name !== 'Error') {
      ElMessage.error('设置失败')
    }
  }
}

// 删除模型版本
const handleDeleteVersion = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除版本「${row.version_name}」吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    deletingVersionId.value = row.id
    const response = await axios.delete(`/api/detection-models/versions/${row.id}`)
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      await fetchModelVersions(currentModel.value.id)
      // 刷新模型列表以更新当前版本信息
      fetchModels()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    // 用户取消删除时不显示错误
    if (error.name !== 'Error') {
      ElMessage.error('删除失败')
    }
  } finally {
    deletingVersionId.value = null
  }
}

// 辅助函数：截断文本
const truncateText = (text, maxLength) => {
  if (!text) return ''
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}

// 组件挂载时获取数据
onMounted(() => {
  fetchModels()
})
</script>

<style scoped>
.detection-models-container {
  padding: 20px;
}

.filter-card,
.data-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.versions-management {
  max-height: 500px;
  overflow-y: auto;
}

.versions-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-end;
}

.text-muted {
  color: #909399;
}
</style>